/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.modules.cspimp.psp.service.impl;

import me.zhengjie.modules.cspimp.psp.domain.Accident;
import me.zhengjie.modules.cspimp.psp.domain.Chemicla;
import me.zhengjie.modules.cspimp.psp.service.dto.AccidentDto;
import me.zhengjie.modules.system.domain.AreaManage;
import me.zhengjie.modules.system.repository.AreaManageRepository;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.cspimp.psp.repository.ChemiclaRepository;
import me.zhengjie.modules.cspimp.psp.service.ChemiclaService;
import me.zhengjie.modules.cspimp.psp.service.dto.ChemiclaDto;
import me.zhengjie.modules.cspimp.psp.service.dto.ChemiclaQueryCriteria;
import me.zhengjie.modules.cspimp.psp.service.mapstruct.ChemiclaMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
 * @author zmm
 * @website https://docs.auauz.net
 * @description 服务实现
 * @date 2020-05-30
 **/
@Service
@RequiredArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class ChemiclaServiceImpl implements ChemiclaService {

    private final ChemiclaRepository chemiclaRepository;
    private final ChemiclaMapper chemiclaMapper;
    private final AreaManageRepository areaManageRepository;

    @Override
    public Map<String, Object> queryAll(ChemiclaQueryCriteria criteria, Pageable pageable) {
        List<Chemicla> page = chemiclaRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder));
        List<ChemiclaDto> chemiclaList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(page)) {
            for (Chemicla chemicla : page) {
                ChemiclaDto chemiclaDto = new ChemiclaDto();
                BeanUtils.copyProperties(chemicla, chemiclaDto);
                AreaManage areaManage = areaManageRepository.findById(chemicla.getUseArea()).orElse(null);
                if (null != areaManage) {
                    chemiclaDto.setUseAreaName(areaManage.getAreaName());
                }
                chemiclaList.add(chemiclaDto);
            }
        }
        return PageUtil.toPage(PageUtil.listPage(chemiclaList, pageable));
    }

    @Override
    public List<ChemiclaDto> queryAll(ChemiclaQueryCriteria criteria) {
        return chemiclaMapper.toDto(chemiclaRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    public ChemiclaDto findById(Long id) {
        Chemicla chemicla = chemiclaRepository.findById(id).orElseGet(Chemicla::new);
        ValidationUtil.isNull(chemicla.getId(), "Chemicla", "id", id);
        return chemiclaMapper.toDto(chemicla);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ChemiclaDto create(Chemicla resources) {
        resources.setCid(0l);
        resources.setStockCount(0);
        return chemiclaMapper.toDto(chemiclaRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Chemicla resources) {
        Chemicla chemicla = chemiclaRepository.findById(resources.getId()).orElseGet(Chemicla::new);
        ValidationUtil.isNull(chemicla.getId(), "Chemicla", "id", resources.getId());
        chemicla.copy(resources);
        chemiclaRepository.save(chemicla);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            chemiclaRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<ChemiclaDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (ChemiclaDto chemicla : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("创建时间", chemicla.getCreateTime());
            map.put("更新时间", chemicla.getUpdateTime());
            map.put("创建者", chemicla.getCreateBy());
            map.put("更新者", chemicla.getUpdateBy());
            map.put("化学品中文名称", chemicla.getChemicalsCn());
            map.put("化学品英文名称", chemicla.getChemicalsEn());
            map.put("化学品别名", chemicla.getChemicalsAlias());
            map.put("cas", chemicla.getChemicalsCas());
            map.put("化学品类别", chemicla.getChemicalsType());
            map.put("化学品文件", chemicla.getChemicalsMsds());
            map.put("供应商名称", chemicla.getSupplierName());
            map.put("供应商联系人", chemicla.getSupplierContactName());
            map.put("供应商联系方式", chemicla.getSupplierContactPhone());
            map.put("咨询单位名称", chemicla.getEmConsultantName());
            map.put("应急联系人", chemicla.getEmContactName());
            map.put("应急联系方式", chemicla.getEmContactPhone());
            map.put("仓库区域", chemicla.getStorageArea());
            map.put("使用区域", chemicla.getUseArea());
            map.put("是否是危险品", chemicla.getIsDangerousGood());
            map.put("危险类型", chemicla.getDangerousCategory());
            map.put("登记号", chemicla.getRegistrationNo());
            map.put("包装类别", chemicla.getPackingCategory());
            map.put("危险特性", chemicla.getHazardCharacteristics());
            map.put("活性危害", chemicla.getActiveHazard());
            map.put("预防及应急措施", chemicla.getPrevention());
            map.put("危规号", chemicla.getHazardNo());
            map.put("禁配物", chemicla.getIncompatibility());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}